//
//  MovieDetailViewController.m
//  LZMPro
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 LZS. All rights reserved.
//

#import "MovieDetailViewController.h"
#import "MoviePlayViewController.h"
#import "MovieModel.h"
#import "MyCollectionViewCell.h"
#import "BaseCollectionView.h"
#import "UIView+Frame.h"
#import <UIImageView+WebCache.h>
#import "RQShineLabel.h"
#import "AVMovieViewController.h"

@interface MovieDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewAccessibilityDelegate,ClickImagetag>


@property(nonatomic, strong) UICollectionView *myCollectionView;
@property(nonatomic, strong) UIImageView *imageView;
//@property(nonatomic, strong) NSMutableArray *modelArray;
@property(nonatomic, assign) NSInteger currentPage;
@property(nonatomic, assign) CGFloat currentoffset;
@property(nonatomic, strong) UIImageView *myImageView;


@property(nonatomic, strong) UIImageView *backImg;
@property(nonatomic, strong) UIImageView *nextImg;
@property(nonatomic, strong) UILabel *titleLabel;
//分割线
@property(nonatomic, strong) UILabel *separateLine;
@property(nonatomic, strong) UILabel *typeLabel;
@property(nonatomic, strong) UILabel *timeLabel;

//详情
@property(nonatomic, strong) RQShineLabel *detailLabel;

//动画图片
@property(nonatomic, strong) UIImageView *animateImag;

//记录滑动的偏移量,用来判断向左滑还是向右划
@property(nonatomic, assign) float currentScroll;

//tableView的scrollSize
@property(nonatomic, assign) CGFloat myScrollSize;

//bool
@property(nonatomic, assign) BOOL isleft;
@property(nonatomic, assign) BOOL isright;
@property(nonatomic, assign) BOOL isstill;

//播放按钮
@property(nonatomic, strong) UIButton *playButton;

@end

@implementation MovieDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化属性
    self.currentPage = 0;
    self.currentoffset = 0;
    self.view.backgroundColor = [UIColor clearColor];
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, self.Vrect.origin.y, self.Vrect.size.width, 0)];
    
    [self.view addSubview:self.backView];
    
    
    //下面背景图
    self.backImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.Vrect.size.width, 0)];
    [self.backImg sd_setImageWithURL:[NSURL URLWithString:self.currentModel.coverBlurred]];
    [self.backView addSubview:self.backImg];
    

    
    
    self.animateImag = [[UIImageView alloc] initWithFrame:self.Vrect];
    [self.animateImag sd_setImageWithURL:[NSURL URLWithString:self.currentModel.coverForDetail]];
    [self.view addSubview:self.animateImag];
    
    //动画效果
    [UIView animateWithDuration:0.5 animations:^{
        self.animateImag.x = 0;
        self.animateImag.y = 0;
        self.animateImag.width = self.view.width;
        self.animateImag.height = 300;
        
        self.backView.frame = CGRectMake(0, 300, CURRENTWIDTH, 300);
        self.backImg.frame = CGRectMake(0, 0, CURRENTWIDTH, 300);
        
        
    }completion:^(BOOL finished) {
        //移除
        [self.animateImag removeFromSuperview];
        
        self.nextImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CURRENTWIDTH, 300)];
        if ((self.currentRow + 1) < self.modelArray.count) {
            [self.nextImg sd_setImageWithURL:[self.modelArray objectAtIndex:self.currentRow + 1]];
        }else{
            //如果是最后一张
            [self.nextImg sd_setImageWithURL:[self.modelArray objectAtIndex:(self.currentRow - 1)]];
        }
        
        [self.backView addSubview:self.nextImg];

        //下面的
        //title
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 375, 30)];
        self.titleLabel.font = [UIFont systemFontOfSize:18 weight:22];
        self.titleLabel.textColor = [UIColor whiteColor];
        self.titleLabel.text = self.currentModel.title;
        [self.backImg addSubview:self.titleLabel];
        
        //分割线
        self.separateLine = [[UILabel alloc] initWithFrame:CGRectMake(10, self.backView.frame.size.height - 252, 140, 1)];
        self.separateLine.backgroundColor = [UIColor whiteColor];
        CGFloat titleWidth = [AppTools widthForCell:self.titleLabel.text];
        CGRect tempRect1 = self.separateLine.frame;
        tempRect1.size.width = titleWidth - 20;
        self.separateLine.frame = tempRect1;
        [self.backImg addSubview:self.separateLine];
        
        //type
        self.typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.backView.frame.size.height - 245 , 50, 20)];
        self.typeLabel.font = [UIFont systemFontOfSize:14];
        self.typeLabel.textColor = [UIColor whiteColor];
        self.typeLabel.text = [NSString stringWithFormat:@"#%@",self.currentModel.category];
        [self.backImg addSubview:self.typeLabel];
        
        //time
        self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, self.backView.frame.size.height - 245 , 120, 20)];
        self.timeLabel.font = [UIFont systemFontOfSize:14];
        self.timeLabel.textAlignment = NSTextAlignmentLeft;
        self.timeLabel.textColor = [UIColor whiteColor];
        self.timeLabel.text = [self numberFormatter:self.currentModel.duration];
        [self.backImg addSubview:self.timeLabel];
        
        //详情
        
        self.detailLabel = [[RQShineLabel alloc] initWithFrame:CGRectMake(10, self.backView.frame.size.height - 230, 355, 200)];
        self.detailLabel.font = [UIFont systemFontOfSize:13];
        self.detailLabel.textColor = [UIColor whiteColor];
        self.detailLabel.numberOfLines = 0;
        self.detailLabel.text = self.currentModel.detailtext;
        CGFloat height = [AppTools heightForCell:self.detailLabel.text];
        CGRect tempRect = self.detailLabel.frame;
        tempRect.size.height = height;
        self.detailLabel.frame = tempRect;
        [self.detailLabel shine];
        
        [self.backImg addSubview:self.detailLabel];
        
        //collectionView
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        //设置item的大小 小方块的大小
        flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, CURRENTHEIGHT);
        //最小行间距
        flowLayout.minimumLineSpacing = 0;
        //最小列间距
        flowLayout.minimumInteritemSpacing = 0;
        //滑动方向
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        //设置item 上左下右的边距大小
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
        //ColletionView
        self.myCollectionView = [[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:flowLayout];
        
        //指定代理人
        self.myCollectionView.delegate = self;
        self.myCollectionView.dataSource = self;
        self.myCollectionView.contentOffset = CGPointMake(self.currentRow * CURRENTWIDTH, 0);
        self.nextImg.alpha = 0;
        self.isstill = YES;
        self.isleft = YES;
        self.isright = YES;
        self.myCollectionView.bounces = NO;
        self.myCollectionView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:self.myCollectionView];
        self.myCollectionView.pagingEnabled = YES;
        
        //注册cell
        [self.myCollectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"mycollectioncell"];
        
        self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.playButton.frame = CGRectMake((315 / 2), 120, 60, 60);
        [self.view addSubview:self.playButton];
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [self.playButton addTarget:self action:@selector(playButtonAction) forControlEvents:UIControlEventTouchUpInside];
        self.playButton.adjustsImageWhenHighlighted = NO;
    }];
}


//代理轻扫手势
-(void)CellSwippeGesture{
    
    
    self.animateImag = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 300)];
    [self.animateImag sd_setImageWithURL:[NSURL URLWithString:self.currentModel.coverForDetail]];
    
    [self.view addSubview:self.animateImag];
    
    [self.myDelegate  changRow:self.currentRow];
    [self.myCollectionView removeFromSuperview];
    
    
    
    [UIView animateWithDuration:1 animations:^{
        
        //判断对应的tableCell是否还处于原先的位置
        if (self.currentRow <= self.last && self.currentRow >= self.first) {
            //仍然处于
            
            CGFloat currentY = self.Vrect.origin.y +(self.currentRow - self.interRow) * 200;
        
            self.Vrect = CGRectMake(self.Vrect.origin.x, currentY, self.Vrect.size.width, self.Vrect.size.height);
            
            self.animateImag.frame = self.Vrect;
            self.backView.frame = CGRectMake(0, self.Vrect.origin.y, self.Vrect.size.width, 0);
            self.backImg.frame = CGRectMake(0, 0, self.Vrect.size.width, 0);
            self.detailLabel.frame = CGRectMake(0, 40, self.Vrect.size.width, self.detailLabel.frame.size.height - 20);
            
        }else{
            //不处于
            
            if (self.currentRow * 200 > (self.scrollSize - CURRENTHEIGHT + 113)) {
                //如果是最后几个
                CGFloat yy = self.currentRow * 200 - ( self.scrollSize - CURRENTHEIGHT + 113);
               
                self.animateImag.frame = CGRectMake(0, yy, self.Vrect.size.width, self.Vrect.size.height);
                self.backView.frame = CGRectMake(0, yy, self.Vrect.size.width, 0);
                self.backImg.frame = CGRectMake(0, 0, self.Vrect.size.width, 0);
                
            }else{
                
                self.animateImag.frame = CGRectMake(0, 0, self.Vrect.size.width, self.Vrect.size.height);
                self.backView.frame = CGRectMake(0, 200, self.Vrect.size.width, 0);
                self.backImg.frame = CGRectMake(0, 0, self.Vrect.size.width, 0);
                
                
            }

        }
        
    }completion:^(BOOL finished) {
        [self.detailLabel removeFromSuperview];
        [self.backImg removeFromSuperview];
        [self.backView removeFromSuperview];
        [self.animateImag removeFromSuperview];
        [self.myDelegate popFromController:self.currentRow];
    }];
    
}


-(void)drawcell:(MovieModel *)model{

    [self.backImg sd_setImageWithURL:[NSURL URLWithString:model.coverBlurred]];
    
    self.titleLabel.text = model.title;
    
    CGFloat titleWidth = [AppTools widthForCell:self.titleLabel.text];
    CGRect tempRect1 = self.separateLine.frame;
    tempRect1.size.width = titleWidth - 20;
    self.separateLine.frame = tempRect1;
    
    self.typeLabel.text = [NSString stringWithFormat:@"#%@",model.category];
    
    self.timeLabel.text = [self numberFormatter:model.duration];
    
    //详情
    
    if (self.detailLabel.isVisible) {
        [self.detailLabel fadeOutWithCompletion:^{
            
            self.detailLabel.text = model.detailtext;
            CGFloat height = [AppTools heightForCell:self.detailLabel.text];
            CGRect tempRect = self.detailLabel.frame;
            tempRect.size.height = height;
            self.detailLabel.frame = tempRect;
            [self.detailLabel shine];
        }];
    }else{

        [self.detailLabel shine];
    }

}

-(NSString *)numberFormatter:(NSNumber *)number{
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSInteger timeTotal = [numberFormatter stringFromNumber:number].integerValue;
    
    if (timeTotal >= 60) {
        NSInteger minute = timeTotal / 60;
        NSInteger seconds = timeTotal % 60;
        
        NSString *timeStr = [NSString stringWithFormat:@" / %ld'%ld\"",minute,seconds];
        
        if (minute < 10) {
            if (seconds < 10) {
                timeStr = [NSString stringWithFormat:@" / 0%ld'0%ld\"",minute,seconds];
            }else{
                timeStr = [NSString stringWithFormat:@" / 0%ld'%ld\"",minute,seconds];
            }
        }
        return  timeStr;
    }else{
        NSString *timeStr = [NSString stringWithFormat:@" / %ld\"",timeTotal];
        return  timeStr;
    }
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.modelArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"mycollectioncell" forIndexPath:indexPath];
    
    MovieModel *model = self.modelArray[indexPath.row];

    cell.model = model;
    cell.index = indexPath.row;
    cell.mydelegate = self;
    
    return cell;
}

//裁剪方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGFloat content = scrollView.contentOffset.x;//scrollview滚动的x坐标
    
    if (content >= 0 && content <= scrollView.contentSize.width - [UIScreen mainScreen].bounds.size.width) {
        //如果不是第一张和最后一张
        
        NSIndexPath *contentIndexPath = [NSIndexPath indexPathForItem:scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width inSection:0];//当前item的下标
        
        
        NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width + 1 inSection:0];//下一个item的下标
        
        MyCollectionViewCell *contentCell = (MyCollectionViewCell *)[self.myCollectionView cellForItemAtIndexPath:contentIndexPath];
        
        MyCollectionViewCell *nextCell = (MyCollectionViewCell *)[self.myCollectionView cellForItemAtIndexPath:nextIndexPath];
        
        float distance = (content - contentIndexPath.item * self.view.frame.size.width);
        
        
        if (distance > CURRENTWIDTH /2) {
            
            
            float dis = (distance -  CURRENTWIDTH /2)/(CURRENTWIDTH /2) ;
            
            self.myImageView.alpha = dis;
            
            
        }else{
            float dis = (distance) / (CURRENTWIDTH /2);
            self.myImageView.alpha = 1 - dis;
            
        }//改变image的透明度
        
        CGRect contentImageViewRect = contentCell.myImageview.frame;
        CGRect nextImageViewRect = nextCell.myImageview.frame;
        contentImageViewRect.origin.x = distance *0.8;
        nextImageViewRect.origin.x =  (distance- CURRENTWIDTH)*0.8 ;
        
        contentCell.myImageview.frame = contentImageViewRect;
        nextCell.myImageview.frame = nextImageViewRect;
        
    }
    
    
    if (scrollView.contentOffset.x < self.currentScroll) {
        //右划
        if ((scrollView.contentOffset.x - self.currentPage *CURRENTWIDTH) < CURRENTWIDTH / 2) {
            self.playButton.alpha = (0.5 - (self.myCollectionView.contentOffset.x - self.currentPage * CURRENTWIDTH) / CURRENTWIDTH) * 2;
            
            NSLog(@"超过一半");
        }else if ((scrollView.contentOffset.x - self.currentPage *CURRENTWIDTH) > CURRENTWIDTH / 2){
            self.playButton.alpha = (self.myCollectionView.contentOffset.x -self.currentPage * CURRENTWIDTH) / (CURRENTWIDTH);
            NSLog(@"没到一半");
        }
        
        
        
        
        if (self.isright == YES) {
            self.isleft = NO;
            
            if ((scrollView.contentOffset.x  - self.currentPage * CURRENTWIDTH) >= 0.05 * CURRENTWIDTH) {
                self.nextImg.alpha = 1 - (self.myCollectionView.contentOffset.x - self.currentPage * CURRENTWIDTH) / CURRENTWIDTH;
                if (self.currentPage < self.modelArray.count) {
                    MovieModel * preModel = [self.modelArray objectAtIndex:(self.currentPage)];
                    if (self.currentPage == 0) {
                        
                    }else{
                        preModel = [self.modelArray objectAtIndex:(self.currentPage)];
                    }
                    
                    if (self.isstill == YES) {
//                        NSLog(@"self.currentPage == %ld",self.currentPage);
                        [self.nextImg sd_setImageWithURL:[NSURL URLWithString:preModel.coverBlurred]];
                        self.isstill = NO;
                    }
                    
                }
            }
            
//            NSLog(@"self.nextImg.alpha==%.2f",self.nextImg.alpha);
        
            
        }
        
    }else{
        
        //button
        if ((scrollView.contentOffset.x - self.currentPage *CURRENTWIDTH) < CURRENTWIDTH / 2) {
            self.playButton.alpha = (0.5 - (self.myCollectionView.contentOffset.x - self.currentPage * CURRENTWIDTH) / CURRENTWIDTH) * 2;
            
            NSLog(@"超过一半");
        }else if ((scrollView.contentOffset.x - self.currentPage *CURRENTWIDTH) > CURRENTWIDTH / 2){
            self.playButton.alpha = (self.myCollectionView.contentOffset.x -self.currentPage * CURRENTWIDTH) / (CURRENTWIDTH);
            NSLog(@"没到一半");
        }

        
        if (self.isleft == YES) {
            self.isright = NO;
            //左划nextImag加载下一张
            self.nextImg.alpha = (self.myCollectionView.contentOffset.x -self.currentPage * CURRENTWIDTH) / CURRENTWIDTH;

            if ((self.currentPage + 1) < self.modelArray.count) {
                MovieModel * nextModel = [self.modelArray objectAtIndex:(self.currentPage + 1)];
                if (self.isstill == YES) {
                    [self.nextImg sd_setImageWithURL:[NSURL URLWithString:nextModel.coverBlurred]];
                    self.isstill = NO;
                }
                
            }
            NSLog(@"222222self.nextImg.alpha == %.2f",self.nextImg.alpha);
        }
        
        
    }
    
    NSLog(@"self.playButton.alpha==%.2f",self.playButton.alpha);

    self.currentPage = scrollView.contentOffset.x / CURRENTWIDTH;
    self.currentScroll = scrollView.contentOffset.x;
}


// 滑动视图，当手指离开屏幕那一霎那，调用该方法。一次有效滑动，只执行一次。
// decelerate,指代，当我们手指离开那一瞬后，视图是否还将继续向前滚动（一段距离），经过测试，decelerate=YES
//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//    
//    
//
//}


// 滚动视图减速完成，滚动将停止时，调用该方法。一次有效滑动，只执行一次。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    NSInteger page = (NSInteger)(scrollView.contentOffset.x / CURRENTWIDTH);
    NSLog(@"page===%ld",page);
    MovieModel *model = [self.modelArray objectAtIndex:page];
    self.currentModel = model;
    [self drawcell:model];
    self.currentRow = page;

    self.nextImg.alpha = 0;
    self.playButton.alpha = 1;
    self.isright = YES;
    self.isleft = YES;
    self.isstill = YES;
}


//播放按钮
-(void)playButtonAction{
    
    MovieModel *model = [self.modelArray objectAtIndex:self.currentPage];
    
    /*
    MoviePlayViewController *MovieVC = [[MoviePlayViewController alloc] init];
    MovieVC.array = [NSArray array];
    MovieVC.array = self.modelArray;
    MovieVC.model = model;
    MovieVC.VedioPlayUrl = model.playUrl;
    
    
    [self presentViewController:MovieVC animated:YES completion:^{
        
        
    }];
    */
    
    AVMovieViewController *AvMovieVC = [[AVMovieViewController alloc] init];
    AvMovieVC.modelArray = [NSArray array];
    AvMovieVC.modelArray = self.modelArray;
    AvMovieVC.model = model;
    AvMovieVC.MoviePlayUrl = model.playUrl;
    
    [self presentViewController:AvMovieVC animated:NO completion:^{
        
        
    }];
    
    
}

//代理方法:点击方法
-(void)didSelectCollection:(NSInteger)index{
    MovieModel *model = [self.modelArray objectAtIndex:index];
    
    /*
     MoviePlayViewController *MovieVC = [[MoviePlayViewController alloc] init];
     MovieVC.array = [NSArray array];
     MovieVC.array = self.modelArray;
     MovieVC.model = model;
     MovieVC.VedioPlayUrl = model.playUrl;
     
     
     [self presentViewController:MovieVC animated:YES completion:^{
     
     
     }];
     */
    //标题数组
    NSMutableArray *titleArray = [NSMutableArray array];
    for (MovieModel *tmodel in self.modelArray) {
        [titleArray addObject:tmodel.title];
    }
    
    AVMovieViewController *AvMovieVC = [[AVMovieViewController alloc] init];
    AvMovieVC.modelArray = [NSArray array];
    AvMovieVC.modelArray = self.modelArray;
    AvMovieVC.model = model;
    AvMovieVC.MoviePlayUrl = model.playUrl;
    AvMovieVC.titleArray = [NSArray arrayWithArray:titleArray];
    NSLog(@"AvMovieVC.titleArray == %@",AvMovieVC.titleArray);
    
    [self presentViewController:AvMovieVC animated:NO completion:nil];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
